# -*- coding: utf-8 -*-
# CreateDate : 2021/12/23 14:49
# Author     : 不肖生
# Github     : https://gitee.com/wxbxs/wuliu_news
# EditDate   : 
# sourceProj : wuliu_news
# Description:
import random
import time
from platform import platform

from selenium import webdriver

from ouyeelMall.constant import Default_User_Agent


class SeleniumBrowser:
    def __init__(self):
        self.chrome_options = self.chrome_options()
        self.browser = self.run_browser()

    def __str__(self):
        """"""
        return "Selenium Crawler."

    @staticmethod
    def chrome_options():
        """"""
        chrome_options = webdriver.ChromeOptions()
        # 无头
        # chrome_options.add_argument('--headless')
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--disable-dev-shm-usage')

        chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_argument('--disable-useAutomationExtension')
        chrome_options.add_argument("--disable-extensions")

        # 设置不加载图片
        chrome_options.add_argument('blink-settings=imagesEnabled=false')
        chrome_options.add_argument(f'User-Agent={Default_User_Agent}')
        return chrome_options

    def run_browser(self):
        """
        :return:
        """
        chrome_options = self.chrome_options
        chrome_options.add_argument("disable-blink-features=AutomationControlled")
        # for windows system
        if "windows" in platform().lower():
            executable_path = r"C:\Users\YW\AppData\Local\Google\Chrome\Application\chromedriver"
        # elif "centos" in platform().lower():
        #     executable_path = "/usr/bin/webdriver"
        else:
            executable_path = "chromedriver"

        browser = webdriver.Chrome(options=chrome_options, executable_path=executable_path)
        # browser.minimize_window()

        browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": """
            Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined
            });
            """
        })

        # browser.maximize_window()
        time.sleep(1 + random.random())

        return browser

    def __del__(self):
        self.browser.close()
        self.browser.quit()


# browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
#             "source": """
#             Object.defineProperty(navigator, "languages", {
#   get: function() {
#     return ["en", "es"];
#   }
# })"""
#         })
#
#         browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
#             "source": """
#                     Object.defineProperty(navigator, "plugins", {
#   get: () => new Array(Math.floor(Math.random() * 6) + 1),
# }); """
#         })
